package com.skycong.hello77.common;

import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.ArrayList;

/**
 * json解析工具
 * Created by Kiki on 2018/6/15.
 */

public class GsonUtil {

    private static final Gson gson = new Gson();

    /**
     * json解析为单个实体
     * @param jsonString
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T jsonToBean(String jsonString,Class<T> cls){
        T t = null;
        try{
            t = gson.fromJson(jsonString,cls);
        }catch (Exception e){
            e.printStackTrace();
        }
        return t;
    }

    /**
     * json解析为实体列表，实体类型为list<T>类型
     * @param jsonString
     * @param type
     * @param <T>
     * @return
     */
    public static <T>ArrayList<T> jsonToList(String jsonString,Type type){
        ArrayList<T> list = new ArrayList<T>();
        try {
            list = gson.fromJson(jsonString, type);
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 将object解析为Json,object可以是T,list<T>,map<T,T>,list<map<T,T>
     * @param object
     * @return
     */
    public static String objectToJson(Object object){
        String jsonString = null;
        try{
            jsonString = gson.toJson(object);
        }catch (Exception e){

        }
        return jsonString;
    }
}
